<?php

namespace app\api\controller;

use alipay\aop\AopClient;
use app\common\controller\Api;
use app\common\library\Pay;
use app\common\model\events\Sign;
use app\common\model\order\Order;
use think\Db;
use think\Env;
use think\Log;

/**
 * 回调接口
 *
 */
class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * 微信回调
     */
    public function wechatNotify()
    {
        $data = file_get_contents('php://input');
        // Log::write('验证支付：' . $data);
        // $data='{"id":"6cc1d6e5-639e-5b62-8f6a-bc0905f1c924","create_time":"2024-01-08T15:58:57+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"DR4Xo51FhGY+gWRM41MjdfjqsiOJ69h5vAcesYLYJnfHhuvtwVuM4LukUlL80w2TiYnF2Tn9EK22LV2y/hXpIrG0jMhbCl8DjWZerAUK7vTIsQoR225nR9+Osq+nICtIn9J/Pvr7Esh9bKFKT4x5FX9BTY0kxbtUK0WtmD9IP0aSirSDLkXcCSGtMH2y/mPmyXB1gvIOxTPl6e9N2cpD26I9YGa287X4/ZV4mUAo/OiJ150qiRpntLI4KPxxIdR1PDbgF1bS1Wz1xum2Rauclbar0XxuThCLjBK0jwqln1yQhBijbS0+sAIxKu3kowmaT1+7aakXOYJDbOQTNtauA6pxSVhZO1nrk/8fzebeT4rqyybGaOwz6GnY349hzDvFhazPsv8MI/b9uf8B6+uRczKRCzAdh2mIZW2TQ8nzlJ64OfYZg228Wp0d9Thc5jrv5mOeUsl/V+s0uWB39q8kTws64sTzLc0geTmUkTVgJSnGPwzN+cZ7PbkWTfTN9PKfUp41l08uIYjwN6AdtdYsMHPRLONeN55o8lbmAlEH2D5BnfJ7gyIC2xuDFTZJQEpCvRvanKwndSs=","associated_data":"transaction","nonce":"t1bIUpNIWYCf"}}';
        $data = json_decode($data, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        // php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            // $APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, Env::get('wechat.apiv3'));
            // $orderData ='{"mchid":"1635149963","appid":"wx1c2ddbc154bece77","out_trade_no":"XX202212081422119380","transaction_id":"4200001642202212085961916819","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"order","success_time":"2022-12-08T14:22:21+08:00","payer":{"openid":"of5sB5sZ4gSQQM6wY6h6KQp1hiWA"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}';
            $orderData = json_decode($orderData, true);

            if ($orderData['trade_state'] == 'SUCCESS') {
                $order_sn = $orderData['out_trade_no']; //商户订单号
                $transaction_id = $orderData['transaction_id']; //微信订单号
                $attach = $orderData['attach']; //微信订单号
                // 启动事务
                Db::startTrans();
                try {
                    /*业务处理*/
                    switch ($attach) {
                        case 'order':
                            $order = Order::get(['sn' => $order_sn]);
                            Pay::orderFulfillment($order, $transaction_id);
                            break;
                    }
                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return 'SUCCESS';
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return 'error';
                }
            }
        }
    }

    //退款回调地址
    public static function refundNotify()
    {
        $notifiedData = file_get_contents('php://input');
        $data = json_decode($notifiedData, true);
        Log::write('验证退款：' . $data);

        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, Env::get('wechat.apiv3'));
            $orderData = json_decode($orderData, true);
            Log::write('退款成功：' . $orderData);

            if ($orderData['refund_status'] == 'SUCCESS') {
                $transaction_id = $orderData['transaction_id']; //退款单号
                $order = Sign::get(['transaction_id' => $transaction_id]);
                if ($order->pay_status == '-1') {
                    return json(['code' => 'SUCCESS', 'message' => '成功']);
                }
                $order->pay_status = '-1';
                $order->canceltime = time();
                $order->cancel_fee = $orderData['amount']['refund'];
                $order->save();
                /*业务处理*/
                return json(['code' => 'SUCCESS', 'message' => '成功']);
            }
        }
    }

    /**
     * 支付宝回调
     */
    public function alipayNotify()
    {
        $post = $_POST;
        if (empty($post)) { //判断POST来的数组是否为空
            return false;
        }
        Log::write('记录日志：' . json_encode($post), 'err');
        $post['fund_bill_list'] = htmlspecialchars_decode($post['fund_bill_list']);
        $aop = new AopClient();
        $alipayrsaPublicKey = config('site.alipay_public_key');
        $check = $aop->rsaCheckV1($post, $alipayrsaPublicKey, "RSA2");
        Log::write('验证结果:' . json_encode($check));
        extract($post);
        if ($check) {
            //商户订单号
            //支付宝交易号
            if ($trade_status == 'TRADE_SUCCESS' || $trade_status == 'TRADE_FINISHED') {
                $str = substr($out_trade_no, 0, 2);
                if ($str == 'NO') {
                    Pay::orderFulfillment($out_trade_no,  $trade_no);
                }
                echo "success";
            } else {
                Log::error('trade_status不存在:');
            }
        } else {
            //验证失败
            echo "fail";   //请不要修改或删除
        }
    }
}
